package com.jms.product.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jms.common.utils.HttpUtils;
import com.jms.product.constant.RegisterSourceEnum;
import com.jms.product.dao.UserBaseDao;
import com.jms.product.entity.UserBaseEntity;
import com.jms.product.service.LoginService;
import com.jms.product.service.RegisterService;
import com.jms.product.vo.SocialUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Jamison
 * @version 1.0
 * @date 2021/6/14 14:53
 */
@Slf4j
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private UserBaseDao userBaseDao;

    @Autowired
    private RegisterService registerService;

    /**
     * 根据从微博授权中获取到的token获取到微博用户信息，并且登录到这个网站中
     * 若用户未曾注册过，就先注册用户，再返回用户信息
     * 若用户已经注册过，就直接查询用户信息并返回
     * @param socialUser 微博授权获取到的信息
     * @return 用户信息
     */
    @Override
    public UserBaseEntity oauth2Login(SocialUser socialUser) {
        //登录和注册合并逻辑
        String uid = socialUser.getUid();
        //1.判断当前用户是否已经登录过系统
        UserBaseEntity userBaseEntity = userBaseDao.selectOne(new QueryWrapper<UserBaseEntity>()
                .eq("social_uid", uid));
        if (userBaseEntity != null) {
            //这个用户已经注册了
            UserBaseEntity updateUserBaseEntity = new UserBaseEntity();
            //更新用户信息
            updateUserBaseEntity.setUid(userBaseEntity.getUid());
            updateUserBaseEntity.setAccessToken(socialUser.getAccess_token());
            updateUserBaseEntity.setExpiresIn(socialUser.getExpires_in());
            updateUserBaseEntity.setSocialUid(uid);
            userBaseDao.updateById(updateUserBaseEntity);
            // 将微博信息添加的用户信息中并返回
            userBaseEntity.setAccessToken(socialUser.getAccess_token());
            userBaseEntity.setExpiresIn(socialUser.getExpires_in());
            userBaseEntity.setSocialUid(uid);
            return userBaseEntity;
        } else {
            //没有查到当前社交用户对应的账户记录，我们就需要注册一个
            UserBaseEntity register = new UserBaseEntity();
            //try catch 防止网络延迟，造成登录失败
            try {
                //3.查询当前社交用户的社交信息（昵称，性别）
                Map<String, String> map = new HashMap<>();
                map.put("access_token", socialUser.getAccess_token());
                map.put("uid", socialUser.getUid());
                HttpResponse response = HttpUtils.doGet("https://api.weibo.com",
                        "/2/users/show.json", "get", new HashMap<String, String>(), map);
                if (response.getStatusLine().getStatusCode() == 200) {
                    //查询成功
                    String s = EntityUtils.toString(response.getEntity());
                    JSONObject jsonObject = JSONObject.parseObject(s);
                    // log.info("jsonObject------>{}", jsonObject);
                    // ......
                    String name = jsonObject.getString("name");
                    String gender = jsonObject.getString("gender");
                    String cover_image_phone = jsonObject.getString("cover_image_phone");
                    register.setNickName(name);
                    register.setUserName(name);
                    register.setGender("m".equals(gender) ? 1 : 0);
                    register.setCreateTime(new Date());
                    register.setFace(cover_image_phone);
                    register.setUpdateTime(register.getCreateTime());
                    register.setRegisterSource(RegisterSourceEnum.SINA_WEIBO.getType());
                    // ......
                    register.setSocialUid(socialUser.getUid());
                    register.setAccessToken(socialUser.getAccess_token());
                    register.setExpiresIn(socialUser.getExpires_in());
                    userBaseDao.insert(register);

                    registerService.initUserAuthWithWeiboLogin(register);
                }
            } catch (Exception e) {
            }

            return register;
        }
    }


}
